<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib uri="/WEB-INF/html.tld" prefix="html" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>


<c:url var="gridId" value="rateCardGrid" />
<c:url var="modelName" value="add" />
<c:url var="windowId" value="rateCardGridWindow" />

                         
<div id='${windowId}'>
	<div><div id="${gridId}"  class='grid'></div></div>
</div>
 




<script>

var linkFormatter = function ( row, cell, value, columnDef, dataContext )
{         return '<a tabindex="0" href="#search-engines" class="fg-button fg-button-icon-right ui-widget ui-state-default ui-corner-all" id="flat"><span class="ui-icon ui-icon-triangle-1-s"></span>flat menu</a>';     }; 
	
var grid${gridId};
var ${gridId}Columns = [
    {id: "srno", name: "Sno", field: "srno"},
    {id: "name", name: "Name", field: "name"},
    {id: "desc", name: "Description", field: "desc"},
    {id: "effectiveDate", name: "Effective Date", field: "effectiveDate"},
    {id: "expiryDate", name: "expiryDate", field: "expiryDate"},
    {id: "vendorId", name: "vendorId", field: "vendorId"},
    {id: "brokerId", name: "brokerId", field: "brokerId"}
    
  ];

 

var ${gridId}Options = {
    enableColumnReorder: false,
	enableCellNavigation: true,
	editable: false,
	autoHeight:true
	
  };
  var selectedRateCards;

  $(function () {
	  
	  $('#rateCardGridWindow').window(
			  {title:"Rate Card Detials"
			  });
	 
	  var ${gridId}GridData = [];
    
    <c:forEach items="${ratecardsList}" var="myItem" varStatus="loopStatus">
     
    ${gridId}GridData[${loopStatus.index}] = {
				srno: '${myItem.rateCardId}',
		        name: '${myItem.name}',
		        desc: '${myItem.description}',
		        effectiveDate: '${myItem.effectiveDate}',
		        expiryDate:'${myItem.expiryDate}',
		        vendorId: '${myItem.vendorId}',
		        brokerId: '${myItem.brokerId}'
		};
      </c:forEach> 
 
      grid${gridId} =buildGrid("#${gridId}", ${gridId}GridData,  ${gridId}Columns,  ${gridId}Options);
		
	  
		var config={grid:grid${gridId}, mode:'recycle', data:${gridId}GridData,action:'ddhich-kyaooon-2'};
		registerForDragDrop(config);
		
		
		grid${gridId}.onClick.subscribe(function(e, args) {
    	
    	var cell = grid${gridId}.getCellFromEvent(e);
    	
        var row = cell.row;
       
        var column = grid${gridId}.getColumns()[cell.cell]; // object containing name, field, id, etc
    	 //alert("Selected asset is " + column.name);
    	 //alert("Selected asset is " + row.name);
    	 //alert("Or " + grid.getDataItem(args.row));
    	 if(column.id=='#')
    	{
    	
    		//alert( $("#rowMenu").css('top'));
    		
    		var offset = $(e.target).offset();
    		//alert(offset.left);
    	 $("#rowMenu").css('right',offset.left+$("#rowMenu").outerWidth());
    	 $("#rowMenu").css('top',offset.top);
    	 $("#rowMenu").css('position','absolute');
    	
    	// alert( $("#rowMenu").css('top'));
    	// alert( $("#rowMenu").css('right'));
    	}
    	 else
    		 {
    		 	<c:url var="url" value="ratebandsajax.ajax" />
    		 	 var cardId =  ${gridId}GridData[cell.row].srno;
    		 	selectedRateCards=cardId;
    		 	 var params = {rateCardId:cardId,rateBandId:'1'};
    		 	var params={url:"${url}",complete:onComplte,error:onError,success:onSuccess,data:params};
    		 	doAjax(params);
    		 }
    	
    	 
    	 
    	});
    function doAjax(config)
    {
    	
    	jQuery.ajax({
			url: config.url,
			data:config.data,
			async: false,
			dataType: "html",
			complete:config.complete,
			error:config.error,
			success:config.success
		});
    }
    
    function onComplte(result)
    {
    	//alert("complete");
    }
    
    function onSuccess(result)
    {
    	
    	$("#assignedRateBand").empty();
    	$("#assignedRateBand").append(result);
    	$("#assignedRateBand").window(
   			  {
   				  footerbuttons:[{}],
   				  headerButtons:[{name:'Submit', onClick:getRateBands,css:'toolbar-plus'}]
   			  });
    	
    /* 	$("#assignedRateBand")
        .bind("dropend", function (e, dd) {
         
        	alert(dd.data);
          alert(dd.rows);
          alert(dd.count);
        }) */
    }
    
    function onError(result)
    {
    	//alert("error");
    }
    
    
    rateCardGrid.onDragInit.subscribe(function (e, dd) {
        // prevent the grid from cancelling drag'n'drop by defaultell
    	//alert('h');
        e.stopImmediatePropagation();
      });
    rateCardGrid.onDragStart.subscribe(function (e, dd) {
        var cell =rateCardGrid.getCellFromEvent(e);
        if (!cell) {
          return;
        }

        dd.row = cell.row;
        if (!rateCardData[dd.row]) {
          return;
        }

        if (Slick.GlobalEditorLock.isActive()) {
          return;
        }

        e.stopImmediatePropagation();
        dd.mode = "recycle";

        var selectedRows = rateCardGrid.getSelectedRows();

        if (!selectedRows.length || $.inArray(dd.row, selectedRows) == -1) {
          selectedRows = [dd.row];
          rateCardGrid.setSelectedRows(selectedRows);
        }

        dd.rows = selectedRows;
        dd.count = selectedRows.length;
       
        

        var proxy = $("<span></span>")
            .css({
              position: "absolute",
              display: "inline-block",
              padding: "4px 10px",
              background: "#e0e0e0",
              border: "1px solid gray",
              "z-index": 99999,
              "-moz-border-radius": "8px",
              "-moz-box-shadow": "2px 2px 6px silver"
            })
            .text("Drag to Menu to add " + dd.count + " selected row(s)")
            .appendTo("body");

        dd.helper = proxy;

        $(dd.available).css("background", "pink");

        return proxy;
      });
       rateCardGrid.onDrag.subscribe(function (e, dd) {
        if (dd.mode != "recycle") {
          return;
        }
        e.stopImmediatePropagation();
        dd.helper.css({top: e.pageY + 5, left: e.pageX + 5});
      });
       rateCardGrid.onDragEnd.subscribe(function (e, dd) {
        if (dd.mode != "recycle") {
          return;
        }
        e.stopImmediatePropagation();
        dd.helper.remove();
        $(dd.available).css("background", "beige");
      });
      $.drop({mode: "mouse"});
      $(".dropzone")
          .bind("dropstart", function (e, dd) {
            if (dd.mode != "recycle") {
              return;
            }
            $(this).css("background", "yellow");
          })
          .bind("dropend", function (e, dd) {
            if (dd.mode != "recycle") {
              return;
            }
            $(dd.available).css("background", "pink");
          })
          .bind("drop", function (e, dd) {
            if (dd.mode != "recycle") {
              return;
            }
            var dataToPass=[];
            var rowsToDelete = dd.rows.sort().reverse();
            for (var i = 0; i < rowsToDelete.length; i++) {
              //data.splice(rowsToDelete[i], 1);
    		 // alert(data[rowsToDelete[i]].srno);
    		  dataToPass.push(rateCardData[rowsToDelete[i]]);
            }
            updateMenu(dataToPass);
           // grid.invalidate();
            rateCardGrid.setSelectedRows([]);
          });
     
     
 
		
  })
  
   function getRateBands()
 {
	 var formData = {rateCardId:selectedRateCards,rateBandId:'2'};
		<c:url var="url" value="ratebands.ajax" />
	  	var params={url:"${url}",complete:_Complete,error:_error,success:showRateCardBands,data:formData,type:"GET",dataType:"text"};
	  	doAjax(params);
	 
 }
 
  
 function showRateCardBands(result)
 {
	 
	
	 $res=$('<div></div>');
	 $res.css('position','absolute');
	 $res.css('left','30');
	 $res.css('top','30');
	 $res.css('z-index','1');
	 
	 $(document.body).append($res);
	 $res.draggable();
	 $res.slideDown('slow');
	 $res.append(result);
	 $res.window(
			  {
				  footerbuttons:[{}],
				  headerButtons:[{}]
			  });
	 
 }
 
</script>